package com.zilue.hfqueue;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by ZD on 2017/5/31.
 */
public class Server {
    private static final int MAX = 100;
    private static final Executor exec = Executors.newFixedThreadPool(MAX);

    public static void main(String[] args) throws IOException {
        /**
         * 基于TCP协议的Socket通信，实现用户登录，服务端
         */
        //1、创建一个服务器端Socket，即ServerSocket，指定绑定的端口，并监听此端口
        ServerSocket serverSocket = new ServerSocket(10086);//1024-65535的某个端口
        System.out.println("Listening port 10086");
        while (true) {
            //2、调用accept()方法开始监听，等待客户端的连接
            final Socket socket = serverSocket.accept();
            exec.execute(() -> {
                try {
                    if (false){
                        ByteBuffer byteBuffer=ByteBuffer.allocate(64);
                        SocketChannel channel = socket.getChannel();
                        StringBuffer stringBuffer=new StringBuffer();
                        while (channel.read(byteBuffer)!=-1)
                            stringBuffer.append(byteBuffer);

                        System.out.println(stringBuffer.toString());
                        return;
                    }
                    //3、获取输入流，并读取客户端信息
                    InputStream is = socket.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader br = new BufferedReader(isr);
                    String info = null;
                    while ((info = br.readLine()) != null) {
                        System.out.println("Hello,我是服务器，客户端说：" + info);
                    }
                    socket.shutdownInput();//关闭输入流

                    //4、获取输出流，响应客户端的请求
                    OutputStream os = socket.getOutputStream();
                    PrintWriter pw = new PrintWriter(os);
                    pw.write("Hello World！ i am the server ,and i received your message!happy everyday!" +
                            "你好，我是服务端，我已经收到了你的消息，祝你快乐每一天！");
                    pw.flush();

                    //5、关闭资源
                    pw.close();
                    os.close();
                    br.close();
                    isr.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        socket.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });

        }
//        serverSocket.close();
    }
}
